package com.iap.client.mediator
{
	import com.iap.admin.event.VectorEvent;
	import com.iap.admin.view.control.FavoriteButton;
	import com.iap.app.AppGlobal;
	import com.iap.client.event.ClientVectorEvent;
	import com.iap.client.event.FavoriteRendererEvent;
	import com.iap.client.event.VectorRendererEvent;
	import com.iap.client.view.ClientView;
	import com.iap.client.view.client.ClientListWindow;
	import com.iap.client.view.control.FavoriteReportButton;
	import com.iap.client.view.favorite.FavoriteEditWindow;
	import com.iap.client.view.instance.InstanceListWindow;
	import com.iap.common.AppSession;
	import com.iap.common.event.ClientEvent;
	import com.iap.common.event.ClientLiteEvent;
	import com.iap.common.mediator.BaseMediator;
	import com.iap.common.model.Client;
	import com.iap.common.model.ClientLite;
	import com.iap.common.model.ClientLiteInstanceLite;
	import com.iap.common.model.Favorite;
	import com.iap.common.model.Instance;
	import com.iap.common.model.InstanceFavorite;
	import com.iap.common.model.InstanceLite;
	import com.iap.common.model.Sample;
	import com.iap.common.model.SampleFiller;
	import com.iap.common.signal.ClientLiteRequestSignal;
	import com.iap.common.signal.ClientRequestSignal;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import mx.collections.ArrayCollection;
	import mx.collections.ArrayList;
	import mx.controls.Alert;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import spark.components.Group;
	import spark.events.IndexChangeEvent;

	public class ClientMediator extends BaseMediator
	{
		[Inject]
		public var view:ClientView;
		[Inject]
		public var clientRequest:ClientRequestSignal;
		[Inject]
		public var clientLiteRequest:ClientLiteRequestSignal;
		
		private var favoriteEditWindow:FavoriteEditWindow;
		private var clientListWindow:ClientListWindow;
		private var instanceListWindow:InstanceListWindow;

		override public function onRegister():void
		{
			addViewListener(MouseEvent.CLICK, handleMouseClick);
			addContextListener(ClientLiteEvent.RESPONSE, clientLiteResponseHandler);
			addContextListener(ClientEvent.RESPONSE, clientResponseHandler);
			view.vectorView.addEventListener(VectorRendererEvent.CLICK, vectorClickViewHanlder);
			view.favoriteDispay.addEventListener(FavoriteRendererEvent.CLICK, favoriteClickHandler);
			view.clientForm.addEventListener(IndexChangeEvent.CHANGE, clientFormChangeHandler);
			view.instanceForm.addEventListener(IndexChangeEvent.CHANGE, instanceFormChangeHandler);
		}
		
		private function clientLiteResponseHandler(evt:ClientLiteEvent):void
		{
			AppGlobal.endWait();
			if(evt.response.task == ClientLiteRequestSignal.GET)
			{
				view.clientForm.selectedIndex = -1;
				view.instanceForm.selectedIndex = -1;
				view.instanceForm.textInput.text = "";
				view.instanceData = new ArrayCollection();
				enableInstanceForm(false);
				view.clientData = new ArrayCollection(evt.response.result as Array);
				view.favoriteDispay.dataProvider = new ArrayCollection();
				updateControlFromSession();
			}
		}
		
		private function updateControlFromSession():void
		{
			if(AppSession.currentClient == null) return;
			var selectedClientLite:ClientLite;
			for(var i:uint = 0; i<view.clientData.length; i++)
			{
				if(view.clientData[i].id == AppSession.currentClient.id)
				{
					selectedClientLite = view.clientData[i];
					view.clientForm.selectedIndex = i;
				}
			}
			if(selectedClientLite == null)
			{
				enableInstanceForm(false);
				return;
			}
			enableInstanceForm(true);
			view.instanceData = new ArrayCollection(selectedClientLite.instanceLites);
			if(AppSession.currentInstance == null) return;
			for(var k:uint = 0; k<view.instanceData.length; k++)
			{
				if(view.instanceData[k].id == AppSession.currentInstance.id)
				{
					view.instanceForm.selectedIndex = k;
				}
			}
			if(view.instanceData == null || view.instanceData.length == 0) return;
			view.favoriteDispay.updateFavorite();
		}
		
		private function clientResponseHandler(evt:ClientEvent):void
		{
			AppGlobal.endWait();
			if(evt.response.task == ClientRequestSignal.GET)
			{
				AppSession.currentClient = evt.response.result as Client;
				AppSession.currentInstance = null;
				if(view.instanceData.length==0) return;
				updateInstance(view.instanceData[0] as ClientLiteInstanceLite);
			}
		}

		private function handleMouseClick(evt:MouseEvent):void
		{
			var propertyName:String = "name";
			var btnName:String = "";
			if(evt.target.hasOwnProperty(propertyName))
			{
				btnName = evt.target[propertyName];
			}
			switch(btnName)
			{
				case "clientEditButton":
				{
					openClientEdit();
					break;
				}
				case "instanceEditButton":
				{
					openInstanceEdit();
					break;
				}
					
				default:
				{
					break;
				}
			}
		}

		private function vectorClickViewHanlder(evt:VectorRendererEvent):void
		{
			if(!validForClientInstance()) return;
			var sample:Sample = new Sample();
			sample.vectorModel = evt.data;
			sample.sampleFillers = [];

			var favorite:Favorite = new Favorite();
			favorite.sample = sample;
			
			var instanceFavorite:InstanceFavorite = new InstanceFavorite();

			instanceFavorite.instanceId = AppSession.currentInstance.id;
			instanceFavorite.favorite = favorite;

			openFavoriteEdit(instanceFavorite);
		}
		
		private function favoriteClickHandler(evt:FavoriteRendererEvent):void
		{
			var instanceFavorite:InstanceFavorite = new InstanceFavorite();
			instanceFavorite.instanceId = AppSession.currentInstance.id;
			instanceFavorite.favorite = evt.data;
			
			openFavoriteEdit(instanceFavorite);
		}
		
		private function openFavoriteEdit(instanceFavorite:InstanceFavorite):void
		{
			if(!validForClientInstance()) return;
			favoriteEditWindow = new FavoriteEditWindow();
			favoriteEditWindow.model = instanceFavorite;
			PopUpManager.addPopUp(favoriteEditWindow, view.root, true);
			PopUpManager.centerPopUp(favoriteEditWindow);
			favoriteEditWindow.addEventListener(CloseEvent.CLOSE, favoriteEditCloseHandler);
			view.root.addEventListener(Event.RESIZE, favoriteEditResizeHandler);
		}
		
		private function favoriteEditResizeHandler(evt:Event):void
		{
			PopUpManager.centerPopUp(favoriteEditWindow);
		}
		
		private function favoriteEditCloseHandler(evt:Event):void
		{
			view.root.removeEventListener(Event.RESIZE, favoriteEditResizeHandler);
			favoriteEditWindow.removeEventListener(CloseEvent.CLOSE, favoriteEditCloseHandler);
			view.favoriteDispay.updateFavorite();
		}

		private function openClientEdit():void
		{
			clientListWindow = new ClientListWindow();
			clientListWindow.clientData = view.clientData;
			PopUpManager.addPopUp(clientListWindow, view.root, true);
			PopUpManager.centerPopUp(clientListWindow);
			clientListWindow.addEventListener(CloseEvent.CLOSE, clientListCloseHandler);
			view.root.addEventListener(Event.RESIZE, clientListResizeHandler);
		}

		private function clientListResizeHandler(evt:Event):void
		{
			PopUpManager.centerPopUp(clientListWindow);
		}
		
		private function clientListCloseHandler(evt:Event):void
		{
			view.clientData = clientListWindow.clientData;
			view.root.removeEventListener(Event.RESIZE, clientListResizeHandler);
			clientListWindow.removeEventListener(CloseEvent.CLOSE, clientListCloseHandler);
			dispatchClientLite();
		}

		private function openInstanceEdit():void
		{
			instanceListWindow = new InstanceListWindow();
			instanceListWindow.instanceData = view.instanceData;
			PopUpManager.addPopUp(instanceListWindow, view.root, true);
			PopUpManager.centerPopUp(instanceListWindow);
			instanceListWindow.addEventListener(CloseEvent.CLOSE, instanceListCloseHandler);
			view.root.addEventListener(Event.RESIZE, instanceListResizeHandler);
		}
		
		private function instanceListResizeHandler(evt:Event):void
		{
			PopUpManager.centerPopUp(instanceListWindow);
		}
		
		private function instanceListCloseHandler(evt:Event):void
		{
			view.instanceData = instanceListWindow.instanceData;
			view.root.removeEventListener(Event.RESIZE, instanceListResizeHandler);
			instanceListWindow.removeEventListener(CloseEvent.CLOSE, instanceListCloseHandler);
			loadClient(AppSession.currentClient.id);
		}
		
		private function clientFormChangeHandler(evt:IndexChangeEvent):void
		{
			var item:ClientLite = view.clientData[evt.newIndex] as ClientLite;
			if(item == null)
			{
				enableInstanceForm(false);
				return;
			}
			view.instanceData = new ArrayCollection(item.instanceLites);
			loadClient(item.id);
		}

		private function loadClient(clientId:int):void
		{
			var client:Client = new Client();
			client.id = clientId;
			AppGlobal.startWait();
			clientRequest.dispatch(client, ClientRequestSignal.GET);
			enableInstanceForm(true);
			view.instanceForm.selectedIndex = 0;
		}
		
		private function dispatchClientLite():void
		{
			AppGlobal.startWait();
			clientLiteRequest.dispatch(new ClientLite(), ClientLiteRequestSignal.GET);
		}

		private function enableInstanceForm(enable:Boolean):void
		{
			view.favoriteReportButton.enabled = enable;
			view.instanceForm.enabled = enable;
			view.instanceButton.enabled = enable;
		}
		
		private function instanceFormChangeHandler(evt:IndexChangeEvent):void
		{
			var selectedItem:ClientLiteInstanceLite = view.instanceData[evt.newIndex] as ClientLiteInstanceLite;
			if(selectedItem == null)
			{
				return;
			}
			updateInstance(selectedItem);
		}
		
		private function updateInstance(selectedItem:ClientLiteInstanceLite):void
		{
			var instance:Instance;
			if(AppSession.currentClient == null) return;
			var instances:Array = AppSession.currentClient.instances;
			for each(var item:Instance in instances)
			{
				if(item.id == selectedItem.instance.id)
				{
					instance = item;
				}
			}
			AppSession.currentInstance = instance;
			view.favoriteDispay.updateFavorite();
		}
		
		private function validForClientInstance():Boolean
		{
			if(AppSession.currentInstance == null)
			{
				Alert.show("Elija el cliente y una instancia.");
				return false;
			}
			return true;
		}
	}
}